package org.scau.studentevaluation.config.global.response;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.scau.studentevaluation.entity.response.Result;
import org.scau.studentevaluation.exception.APIException;
import org.scau.studentevaluation.util.ResultUtil;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.lang.reflect.ParameterizedType;

/**
 * @ClassName: ResponseControllerAdvice
 * @Description: TODO
 * @Author: sunslikes
 * @Date: 2020/6/26 12:51
 * @Version: 1.0
 * 用于包装接口的数据
 */
@Slf4j
@RestControllerAdvice(basePackages = {"org.scau.studentevaluation.controller"})
public class ResponseControllerAdvice implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter methodParameter,
                            Class<? extends HttpMessageConverter<?>> aClass) {
        // 如果接口返回的类型本身就是ResultVO类就不用进行额外操作，返回false
//        return !methodParameter.getGenericParameterType().equals(ResultVO.class);
        // 为了让泛型也能返回，虽说没这个必要
        if (methodParameter.getGenericParameterType().equals(Result.class)) {
            return false;
        } else if (methodParameter.getGenericParameterType() instanceof ParameterizedType) {
            /**
             * 返回的参数将会是sun.reflect.generics.reflectiveObjects，用它原生的equal也可以
             */
            ParameterizedType type = (ParameterizedType) methodParameter.getGenericParameterType();
            return !type.getRawType().equals(Result.class);
        }
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object data, MethodParameter methodParameter,
                                  MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass,
                                  ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        // String类型不能直接包装，所以要进行些特别的处理
        if (methodParameter.getGenericParameterType().equals(String.class)) {
            ObjectMapper objectMapper = new ObjectMapper();
            try {
                // 将数据包装在ResultVO里面后，再转换为json字符串响应给前端
                return objectMapper.writeValueAsString(ResultUtil.success(data));
            } catch (JsonProcessingException  e) {
                throw new APIException("返回String类型错误");
            }
        }
        // 将原本的数据包装在ResultVO里
        return ResultUtil.success(data);
    }
}
